package com.wash.shoes.domain.wx;


import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.R;
import com.wash.shoes.entity.OrderPo;
import com.wash.shoes.service.OrderService;
import com.wash.shoes.util.WsRandomUtil;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.AmountReq;
import com.wechat.pay.java.service.refund.model.CreateRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 微信支持的处理
 */
@Service
public class WxPayProcess {

    private static final Logger log = LoggerFactory.getLogger("pay-record");

    @Autowired
    RefundService refundService;

    @Autowired
    OrderService orderService;

    /**
     * 微信支付退款
     *
     * @param orderPo
     * @return
     */
    public String refund(OrderPo orderPo) {

        try {
            String wxOutRefundNo = orderPo.getId() + WsRandomUtil.generateByRandom(10);
            orderPo.setWxOutRefundNo(wxOutRefundNo);
            CreateRequest request = new CreateRequest();
            //设置退款金额 根据自己的实际业务自行填写
            AmountReq amountReq = new AmountReq();
            amountReq.setRefund(Long.valueOf((long) (orderPo.getTotalPrice() * 100)));
            amountReq.setTotal(amountReq.getRefund());
            amountReq.setCurrency("CNY");
            request.setAmount(amountReq);
            //支付成功后回调回来的transactionId 按照实际情况填写
            request.setTransactionId(orderPo.getWxTransactionId());
            request.setOutTradeNo(orderPo.getWxOutTradeNo());
            //支付成功后回调回来的transactionId 按照实际情况填写
            request.setOutRefundNo(orderPo.getWxOutRefundNo());
            //退款成功的回调地址
            request.setNotifyUrl("https://www.shoeswasher.com/mobile-api/customer/wxpayOrderRefund");
            //发起请求,申请退款
            com.wechat.pay.java.service.refund.model.Refund refund = refundService.create(request);
            //调用成功的响应数据
            System.out.println(refund);
            R.ok(JSON.toJSONString(refund));
            orderService.updateById(orderPo);
            return "success";
        } catch (Exception e) {
            log.error("微信支付失败的信息");
            log.error("微信支付失败的信息 {}", e);
            return e.getMessage();
        }
    }
}
